package org.controller;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.entity.Books;
import org.service.BooksService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping(value = "/ajax2")
public class AjaxController2 {
    @Resource
    private BooksService booksService;
    @RequestMapping(value = "/list01")
    public void list01(HttpServletResponse response) throws IOException {
        Books books1 = new Books(1,"book01",20,"author01");
        Books books2 = new Books(2,"book02",20,"author02");
        Books books3 = new Books(3,"book04",20,"author03");
        List<Books> booksList = new ArrayList<>();
        booksList.add(books1);
        booksList.add(books2);
        booksList.add(books3);
        String jsonString = JSON.toJSONString(booksList);
        PrintWriter out = response.getWriter();
        out.println(jsonString);//ajax返回使用out.println();输出返回
    }
    @RequestMapping(value = "/bookslist")
    public void bookslist(HttpServletResponse response) throws IOException {
        //通过service获得分页的list信息
        ObjectMapper mapper = new ObjectMapper();

        List<Books> booksList = booksService.queryAllByLimit(0, 3);
        //将获取的list信息转化为json字符串
        String bookslistjson = mapper.writeValueAsString(booksList);
        PrintWriter out = response.getWriter();
        System.out.println(bookslistjson);
        //ajax前端获取返回的list的json字符串
        out.println(bookslistjson);
    }


    @RequestMapping(value = "/page")
    public void pagelist(HttpServletResponse response) throws IOException {
        //通过service获得分页的list信息
        ObjectMapper mapper = new ObjectMapper();

        List<Books> booksList = booksService.queryAllByLimit(0, 3);
        //将获取的list信息转化为json字符串
        String bookslistjson = mapper.writeValueAsString(booksList);
        PrintWriter out = response.getWriter();
        System.out.println(bookslistjson);
        //ajax前端获取返回的list的json字符串
        out.println(bookslistjson);
    }
    @RequestMapping(value = "/pagelist")
    public String bookpage(Model model) throws JsonProcessingException {
        //通过service获得分页的list信息
        ObjectMapper mapper = new ObjectMapper();

        List<Books> booksList = booksService.queryAllByLimit(0, 3);
        model.addAttribute("bookslist",booksList);
        return "booklist";
    }
}
